package cn.dataling.ai.filter;

import cn.dataling.ai.common.Response;
import cn.dataling.ai.common.ResponseStatusCodeEnum;
import cn.dataling.ai.component.JacksonComponent;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

/**
 * @coder taoym
 * @datetime 2021/10/8 17:26
 * @desc 请求源过滤器 查看是否为小程序请求
 */
public class RequestSourceFilter implements Filter {

    private final JacksonComponent jacksonComponent;

    public RequestSourceFilter(JacksonComponent jacksonComponent) {
        this.jacksonComponent = jacksonComponent;
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String userAgent = request.getHeader("User-Agent");
        if (userAgent.contains("Android") || userAgent.contains("iPhone")) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        Response<Object> resp = Response.fail(ResponseStatusCodeEnum.REQUEST_SOURCE_IS_NOT_LEGAL, null);
        response.getWriter().append(jacksonComponent.toJson(resp));
    }
}
